﻿using BamaTeaWebAPI.Models;
using BamaTeaWebAPI.Models.FXModels;
using CSCommonUtils;
using FX_API.Models;
using FX_API.Request;
using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BamaTeaWebAPI.Services
{
    public class FeiyuService
    {
        protected ILog logger = LogManager.GetLogger("FeiyuService");
        protected FXLeadsQueryService fxLeadsQueryService = new FXLeadsQueryService();

        public bool UploadToFX(FeiyuRequestModel requestModel)
        {
            var lead = fxLeadsQueryService.GetLeadByTel(requestModel.telphone);
            if (lead != null)
            {
                logger.Info($"从飞鱼上传信息出现重复手机号, 数据信息: {JsonConvert.SerializeObject(requestModel)}");
                return true;
            }

            // 获取纷享的请求对象
            var fxRequestModel = Map2FXLeadsModel(requestModel);

            FXCommonUploadRequest uploadRequest = new FXCommonUploadRequest();
            uploadRequest.exceptionHandler += (Exception ex) =>
            {
                logger.Error($"从飞鱼上传信息失败，错误信息: {ex.Message}, 错误堆栈: {ex.StackTrace}, 数据信息: {JsonConvert.SerializeObject(requestModel)}");
            };
            uploadRequest.httpErrHandler += (string responseMsg, FXCreateRequestModel request) =>
            {
                logger.Error($"从飞鱼上传信息失败，返回信息: {responseMsg}数据信息: {JsonConvert.SerializeObject(requestModel)}");
            };
            var result = uploadRequest.Upload(fxRequestModel);

            if (result != null && result.errorCode != 0)
            {
                logger.Info($"从飞鱼上传到纷享发生错误, 返回信息: {JsonConvert.SerializeObject(result)} 数据信息: {JsonConvert.SerializeObject(requestModel)}");
            }

            logger.Info($"从飞鱼上传到纷享成功，数据信息: {JsonConvert.SerializeObject(requestModel)}");

            return result != null && result.errorCode == 0;
        }

        private FXLeadsObjCreateModel Map2FXLeadsModel(FeiyuRequestModel model)
        {
            return new FXLeadsObjCreateModel() 
            { 
                name = model.name,
                tel = model.telphone,
                field_d38Vb__c = string.IsNullOrEmpty(model.city_name) ? model.location : model.city_name,
                field_3TSkg__c = string.IsNullOrEmpty(model.province_name) ? model.location : model.province_name,
                field_9fehL__c = (long) TimeParser.ConvertDateTimeInt(DateTime.Now),
                source = GetSource(model.app_name)
            };
        }

        private Dictionary<string, string> sourceMap = new Dictionary<string, string>()
        {
            { "今日头条", "4" },
            { "抖音", "lk6V7J5Bk" },
            { "搜索广告", "ZcJLj6821" }
        };
        private string GetSource(string sourceId)
        {
            if (!sourceMap.ContainsKey(sourceId)) return null;
            return sourceMap[sourceId];
        }
    }
}